from django.shortcuts import render
from django.views import View
from django.http import HttpResponseRedirect, JsonResponse
from reservation.models import Reservation
from .models import *

# Create your views here.


#新品海报
class CarFlashView(View):
    def get(self,request):
        user = request.session.get('user')
        product_list = Product.objects.all()
        productimage_list = ProductImage.objects.all()
        if user:
            reservation_list = Reservation.objects.filter(user_id=user.id)
            number= len(reservation_list)
            return render(request, './templates/flashsale/car_flashsale.html',
                          {'product_list': product_list, 'productimage_list': productimage_list, 'number': number})
        else:
            return render(request,'./templates/flashsale/car_flashsale.html',{'product_list':product_list,'productimage_list':productimage_list})


#责任声明书
class ReservstcarView(View):
    def get(self,request):
        return render(request,'./templates/flashsale/reservatcar.html')


#添加活动
class AddproductView(View):
    def get(self,request):
        user = request.session.get('user')
        productid = request.GET.get('productId')
        product = Product.objects.get(id=productid)
        if Active.objects.filter(product_id=productid).exists():
            return JsonResponse({'message':'已参与'})
        elif user == None:
            return JsonResponse({'message': '请先登入'})
        else:
            Active.objects.create(model=product.model,
                                  name=product.name,
                                  img=product.img,
                                  price=product.price,
                                  rank=product.rank,
                                  endurance=product.endurance,
                                  charge=product.charge,
                                  users_id=user.id,
                                  product_id=productid)
            product.count = product.count - 1
            product.save()
            return JsonResponse({'message': '参与成功'})



#删除活动
class DleteactiveView(View):
    def get(self,request,p_id):
        active = Active.objects.get(id=p_id)
        active.delete()
        product = Product.objects.get(id=active.product_id)
        product.count = product.count + 1
        product.save()
        return HttpResponseRedirect('/activity/')
